<?php
/**
 * Jishupu-Laravel-Vue-Admin
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Models;

use App\Filters\UserFilter;
use App\Traits\BaseModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

/**
 * 管理员模型
 *
 * Class User
 * @package App\Models
 */
class User extends Authenticatable
{
    use BaseModel;
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * 指定表名
     */
    protected $table = 'user';

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [];

    /**
     * 不能被批量赋值的属性
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes that should be hidden for serialization.
     * 数据显示时，设置了敏感信息字段数据中不显示
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'randstr',
        'deleted_at',
        'created_at',
        'updated_at',
        'created_user_id',
        'last_login_time',
        'login_fail_times'
    ];

    /**
     * The attributes that should be cast.
     * 显示数据时类型转换
     *
     * @var array
     */
    protected $casts = [
//        'email_verified_at' => 'datetime',
    ];

    /**
     * 注册过滤器
     * @param $query
     * @param UserFilter $filters
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeFilter($query, UserFilter $filters)
    {
        return $filters->apply($query);
    }


    /**
     * 关联管理员角色关系表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function userRole()
    {
        return $this->hasMany(UserRole::class, 'user_id', 'id');
    }

    /**
     * 关联删除管理员角色关系表数据
     */
    protected static function boot()
    {
        parent::boot();
        static::deleted(function ($model) {
            $model->userRole()->delete();
        });
    }

}
